
using System;
using System.IO;
using System.Text;

namespace BlogBackUp
{
    public class CommonUtils
    {
        public static void SaveFile(String directory, String fileName, Byte[] contents)
        {
            ValidateFileName(ref fileName);
            DirectoryInfo dir = new DirectoryInfo(directory);
            if (!dir.Exists)
                dir.Create();            
            String fileFullPath = directory + fileName;
            // Create a new file.
            FileStream fs = new FileStream(fileFullPath, FileMode.Create);
            BinaryWriter w = new BinaryWriter(fs);

            w.Write(contents);
            // Make sure all data is written from the internal buffer.
            w.Flush();

            // Close the file.
            w.Close();
            fs.Close();

        }

        public static void SaveFile(String directory, String fileName, String contents)
        {
            ValidateFileName(ref fileName);
            DirectoryInfo dir = new DirectoryInfo(directory);
            if (!dir.Exists)
                dir.Create();
            String fileFullPath = directory + fileName;
            // Create a new file.
            FileStream fs = new FileStream(fileFullPath, FileMode.Create);
            StreamWriter w = new StreamWriter(fs, Encoding.UTF8);

            w.Write(contents);
            // Make sure all data is written from the internal buffer.
            w.Flush();

            // Close the file.
            w.Close();
            fs.Close();
        }

        public static bool IsImg(String ext)
        {
            if (ext.ToLower() == ".jpg"
               || ext.ToLower() == ".gif"
               || ext.ToLower() == ".png")
            {
                return true;
            }
            return false;
        }
        public static void ValidateFileName(ref String fileName)
        {
            char [] inValidateChars = {'/','\\',':','*','?','\"','|','<','>'};            
            foreach(char ch in inValidateChars)
            {
               fileName = fileName.Replace(ch,' ');
            }
        }
    }
}